import serial
import serial.tools.list_ports
import struct

from tkinter import messagebox


port_list = []
serial_port : serial.Serial = None
def get_port_list():
    global port_list
    port_list = list(serial.tools.list_ports.comports())

    return port_list

def open_port(port_name:str, baudrate:int=115200):
    global serial_port

    if serial_port != None:
        try:
            serial_port.close()
        except:
            pass

    serial_port = None

    print(f"串口打开中...{port_name}")



    try:
        serial_port = serial.Serial(port_name, baudrate, timeout=1)
        messagebox.showinfo("提示", "串口打开成功")

    except Exception as e:
        messagebox.showerror("错误", "串口打开失败")
        print(e)

def serial_write(send_data:list):
    send_data = struct.pack("%dB"%(len(send_data)), *send_data)
    
    try:
        serial_port.write(send_data)
    except:
        pass
    print(send_data)
def serial_close():
    if(serial_port != None):
        try:
            serial_port.close()
        except:
            pass
